package com.example.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.room.ZRoomDB;
import com.example.room.course.Course;
import com.example.room.course.CourseDao;
import com.example.xc.R;
import com.example.room.DbManager;

public class AddCourseActivity extends AppCompatActivity {

    EditText etCourseNo;
    EditText etCourseName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_course);
        findViewById(R.id.back).setOnClickListener(v -> finish());
        etCourseNo = findViewById(R.id.et_course_no);
        etCourseName=findViewById(R.id.et_course_name);
        findViewById(R.id.btn_add).setOnClickListener(v -> {
            int result=addCourse();
            if(result==1){
                Toast.makeText(getBaseContext(), "添加成功", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getBaseContext(), "添加失败", Toast.LENGTH_SHORT).show();
            }
            finish();
        });
    }

    public int addCourse(){
        try {
            ZRoomDB zRoomDB = DbManager.INSTANCE.getDB(getBaseContext());
            CourseDao courseDao = zRoomDB.courseDao();
            Course lastUser = courseDao.queryUserMax();
            int id = 1;
            if (lastUser != null) {
                id = lastUser.getId() + 1;
            }
            Course user = new Course(id, etCourseNo.getText().toString().trim(), etCourseName.getText().toString().trim());
            courseDao.addDesk(user);
            return 1;
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}